(function($) {

    // 1. image uploaded
    // 2. inject angular directives to image field
    // 3. init the angular app

    var app = angular.module('app', ['ngSanitize']);

    app.filter('toPixel', function() {
        return function(item) {
            if (item) {
                var left = 'left:' + item.x + '%;';
                var top = 'top:' + item.y + '%;';
                return left + top;
            } else {
                return '';
            }
        };
    });

    app.directive('ngUpdateHidden',function() {
        return function(scope, el, attr) {
            var model = attr['ngModel'];
            scope.$watch(model, function(nv) {
                el.val(nv);
            });
        };
    });

    app.controller('ctrl', function($scope, $timeout, $compile) {

        window.$scope = $scope;

        angular.element(document).ready(function() {

            // cache DOM
            var $win = $(window);
            var $doc = $(document);
            var $form = $('.node-xenyo_sc_styling_article-form');
            var $hiddenField = $('.field-name-field-pins-data textarea');
            var $img = $('.field-name-field-image .image-preview img:eq(0)');
            var imgH, imgW, $wrapper;
            var api = '/api/v1/search/styling_item?query=';

            function update() {
                $timeout(function() {
                    $scope.$apply();
                });
            }

            $scope.$watch('form', function(nv, ov) {
                if (nv !== ov) {
                    $hiddenField.val(Base64.encode(angular.toJson($scope.form)));
                    $scope.form.pins.length && angular.forEach($scope.form.pins, function(v,k) {
                        $scope.form.pins[k].showInThumb = (k === parseInt(nv.showInThumb));
                    });
                }
            }, true);


            $scope.onType = function(e, pin) {
                pin.nid = '';
                pin.data = [];
                $.get(api + pin.title, function(data) {
                    // console.log('API successfully returned:', data);
                    pin.data = data;
                    update();
                }).fail(function() {
                    console.error("API error");
                })
            };

            $scope.onSelect = function(e, pin, option) {
                pin.nid = option.nid;
                pin.title = option.title;
                pin.data = [];
                update();
            }

            if (!$img.length) {
                $doc.ajaxComplete(function(event, xhr, settings) {
                    if (settings.url.indexOf('/file/ajax/field_image') === 0) {
                        var timer = setInterval(function() {
                            if ($('.field-name-field-image .image-preview img:eq(0)').length) {
                                $img = $('.field-name-field-image .image-preview img:eq(0)');
                                clearInterval(timer);
                                injectNg();
                            }
                        }, 200);
                    }
                });
            } else {
                injectNg();
            }

            function injectNg() {
                imgH = $img.outerHeight(true);
                imgW = $img.outerWidth(true);

                if (!$('.img-wrapper').length) {
                    $img.attr('ng-click','addPin($event)');
                    $img.wrap('<div class="img-wrapper"></div>');

                    var pinHtml = '<div class="pin" ng-repeat="(key, p) in form.pins" style="{{p | toPixel}}" ng-class="{disabled: p.status == 0}">' +
                          '<input type="text" ng-model="p.title" ng-keyup="onType($event, p)" />' +
                          '<div class="pin-select" ng-show="p.data.length > 0">' +
                            '<div class="pin-option" ng-repeat="(k2, d) in p.data" ng-click="onSelect($event, p, d)" ng-bind="d.title"></div>' +
                          '</div>' +
                          '<button ng-click="removePin(key)">X</button>' +
                          '<div class="pin-thumb">' +
                              '<label><input type="radio" class="pin-show" name="show-in-thumb" ng-model="form.showInThumb" ng-value="key" />Show In Thumbnail</label>' +
                              '<div class="pin-direction" ng-show="form.showInThumb == key">' +
                                  '<label><input type="radio" name="direction-{{key}}" ng-model="p.direction" value="1" />TL</label>' +
                                  '<label><input type="radio" name="direction-{{key}}" ng-model="p.direction" value="2" />TR</label>' +
                                  '<label><input type="radio" name="direction-{{key}}" ng-model="p.direction" value="3" />BL</label>' +
                                  '<label><input type="radio" name="direction-{{key}}" ng-model="p.direction" value="4" />BR</label>' +
                              '</div>' +
                          '</div>' +
                      '</div>';
                    $wrapper = $img.parent();
                    // $wrapper.after('<pre ng-bind="form | json"></pre>');
                    $wrapper.append(pinHtml);

                    $compile($form.children())($scope);
                    $timeout(function() {
                        $scope.$apply();
                        initNg();
                    })
                }

            }

            function initNg() {
                if ($hiddenField.val().length === 0) {
                    $scope.form = {
                        showInThumb: 0,
                        pins: []
                    }
                } else {
                    $scope.form = angular.fromJson(Base64.decode($hiddenField.val()));
                    if ($scope.form.showInThumb === null) {
                        $scope.form.showInThumb = 0;
                    }
                }


                $scope.addPin = function(e) {
                    if ($scope.form.pins.length < 10) {
                        var obj = {
                            x: (e.offsetX / imgW) * 100,
                            y: (e.offsetY / imgH) * 100,
                            nid: '',
                            title: '',
                            data: [],
                            direction: "1", // 1:TL, 2:TR, 3:BL, 4:BR
                            showInThumb: false,
                        };
                        $scope.form.pins.push(obj);
                        $timeout(function() {
                            $scope.$apply();
                            $('.pin').last().find('input[type="text"]').focus();
                        });
                    } else {
                        alert('10 Pins is the MAX!');
                    }
                };
                $scope.removePin = function(key) {
                    $scope.form.pins.splice(key, 1);
                };
                $scope.removeAllPin = function() {
                    $scope.form.pins = [];
                };
                $scope.randomScale = function() {
                    var random = Math.random();
                    while (random < 0.5) {
                        random = Math.random();
                    }
                    $outimg.animate({
                        width: random * 600
                    }, 300);
                };
            }
        });

    });

    var Base64 = {_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};




})(jQuery);
